import * as _ from "lodash"
import { camelCase, snakeCase } from "../case"
import { PageList } from "../data"
import httpClient from "../httpclient"
import { Recipient } from "./recipient"

export class WithdrawalQuery {

  private params = {}

  public page(page?: string | number): WithdrawalQuery {
    if (page) {
      this.params["page"] = page
    }
    return this
  }

  public limit(limit?: string | number): WithdrawalQuery {
    if (limit) {
      this.params["limit"] = limit
    }
    return this
  }

  public accountId(accountId?: string): WithdrawalQuery {
    this.params["account_id"] = accountId
    return this
  }

  public statuses(statuses?: string): WithdrawalQuery {
    if (statuses) {
      this.params["statuses"] = statuses
    }
    return this
  }

  public appliedTimeStart(appliedTimeStart?: string): WithdrawalQuery {
    if (appliedTimeStart) {
      this.params["applied_time_start"] = appliedTimeStart
    }
    return this
  }

  public appliedTimeEnd(appliedTimeEnd?: string): WithdrawalQuery {
    if (appliedTimeEnd) {
      this.params["applied_time_end"] = appliedTimeEnd
    }
    return this
  }

  public list(): Promise<PageList<Withdrawal>> {
    return httpClient.get("/v1/withdrawals", {
      params: this.params,
    }).then(({ data }) => data)
      .then(camelCase)
      .then(data => {
        return _.assign(new PageList<Withdrawal>(), data, {
          elements: _.map(data.elements, withdrawal => _.assign(new Withdrawal(), withdrawal)),
        })
      })
  }

}

export enum WithdrawalStatus {
  Pending = "pending",
  Processing = "processing",
  Disapproved = "disapproved",
  Succeeded = "succeeded",
  Failed = "failed",
  Canceled = "canceled"
}


export class Withdrawal {
  public id: string
  public accountId: string
  public currencyCode: string
  public amount: string
  public recipient: Recipient
  public status: WithdrawalStatus
  public memo: string
}

export class WithdrawalServiceV1 {

  public static createWithdrawalQuery() {
    return new WithdrawalQuery()
  }

  public static applyWithdrawal(withdrawal: Withdrawal): Promise<Withdrawal> {
    return httpClient.post(`/v1/withdrawals`, snakeCase(withdrawal))
      .then(({ data }) => data)
      .then(camelCase)
      .then(data => _.assign(new Withdrawal(), data))
  }

  public static cancelWithdrawal(withdrawalId: string): Promise<Withdrawal> {
    return httpClient.post(`/v1/withdrawals/${withdrawalId}/cancel`)
      .then(({ data }) => data)
      .then(camelCase)
      .then(data => _.assign(new Withdrawal(), data))
  }

  public static getWithdrawal(withdrawalId: string): Promise<Withdrawal> {
    return httpClient.get(`/v1/withdrawals/${withdrawalId}`)
      .then(({ data }) => data)
      .then(camelCase)
      .then(data => _.assign(new Withdrawal(), data))
  }
}
